package com.micro.school.system.service.impl;

import java.util.Date;
import java.util.List;

import com.micro.school.common.core.context.SecurityContextHolder;
import com.micro.school.common.core.domain.R;
import com.micro.school.common.core.utils.StringUtils;
import com.micro.school.common.core.web.domain.AjaxResult;
import com.micro.school.common.security.utils.SecurityUtils;
import com.micro.school.system.api.RemoteEduService;
import com.micro.school.system.api.domain.vo.*;
import com.micro.school.system.api.factory.RemoteFileFallbackFactory;
import com.micro.school.system.api.model.LoginUser;
import com.micro.school.system.domain.StudentInfo;
import com.micro.school.system.domain.vo.BatchLogDetailVo;
import com.micro.school.system.domain.vo.StudentInfoVo;
import com.micro.school.system.mapper.BatchLogDetailMapper;
import com.micro.school.system.mapper.StudentInfoMapper;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.micro.school.system.mapper.StudentBatchLogMapper;
import com.micro.school.system.domain.StudentBatchLog;
import com.micro.school.system.domain.vo.StudentBatchLogVo;
import com.micro.school.system.convert.student.StudentBatchLogConvert;
import com.ruoyi.system.service.IStudentBatchLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author rakic
 * @date 2025-08-05
 */
@Service
public class StudentBatchLogServiceImpl extends ServiceImpl<StudentBatchLogMapper,StudentBatchLog> implements IStudentBatchLogService
{
    @Autowired
    private StudentBatchLogMapper studentBatchLogMapper;

    @Autowired
    private BatchLogDetailMapper batchLogDetailMapper;

    @Autowired
    private StudentInfoMapper studentInfoMapper;

    @Resource
    private RemoteEduService remoteEduService;

    private static final Logger log = LoggerFactory.getLogger(StudentBatchLogServiceImpl.class);

    /**
     * 查询【请填写功能名称】
     * 
     * @param batchId 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public StudentBatchLogVo selectStudentBatchLogByBatchId(String batchId)
    {

        return studentBatchLogMapper.selectStudentBatchLogByBatchId(batchId,Integer.parseInt(SecurityContextHolder.getUserTenantId()));
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param studentBatchLogVo 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<StudentBatchLogVo> selectStudentBatchLogList(StudentBatchLogVo studentBatchLogVo)
    {
        if (!SecurityContextHolder.getUserName().equals("admin")) {
            studentBatchLogVo.setCreateAt(SecurityContextHolder.getUserName());
        }
        return studentBatchLogMapper.selectStudentBatchLogList(studentBatchLogVo);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param studentBatchLogVo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertStudentBatchLog(StudentBatchLogVo studentBatchLogVo,String status)
    {
        if (status != null && !"".equals(status)){
            studentBatchLogVo.setStatus(2L);
        }else{
            studentBatchLogVo.setStatus(1L);
        }
        StudentBatchLog studentBatchLog = StudentBatchLogConvert.convertToEntity(studentBatchLogVo);
        studentBatchLog.setCreateAt(SecurityContextHolder.getUserName());
        studentBatchLog.setTenantId(Integer.parseInt(SecurityContextHolder.getUserTenantId()));
        return studentBatchLogMapper.insertStudentBatchLog(studentBatchLog);

    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param studentBatchLogVo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateStudentBatchLog(StudentBatchLogVo studentBatchLogVo)
    {
        StudentBatchLog studentBatchLog = StudentBatchLogConvert.convertToEntity(studentBatchLogVo);
        return studentBatchLogMapper.updateStudentBatchLog(studentBatchLog);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param batchIds 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteStudentBatchLogByBatchIds(List<String> batchIds)
    {

        return studentBatchLogMapper.deleteStudentBatchLogByBatchIds(batchIds,Integer.parseInt(SecurityContextHolder.getUserTenantId()));
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param batchId 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteStudentBatchLogByBatchId(String batchId)
    {

        return studentBatchLogMapper.deleteStudentBatchLogByBatchId(batchId,Integer.parseInt(SecurityContextHolder.getUserTenantId()));
    }

    @Override
    public String processBatchUpload(String batchId, long graduateStatus) {
        Integer tenantId = Integer.parseInt(SecurityContextHolder.getUserTenantId());

        // 检查是否有错误数据
        BatchLogDetailVo errorQuery = new BatchLogDetailVo();
        errorQuery.setBatchId(batchId);
        errorQuery.setStatus(2L);
        errorQuery.setTenantId(tenantId);
        List<BatchLogDetailVo> errorRecords = batchLogDetailMapper.selectBatchLogDetailList(errorQuery);

        if (!errorRecords.isEmpty()) {
            return "有错误信息，重新导入失败！";
        }

        // 获取待处理的数据
        BatchLogDetailVo validQuery = new BatchLogDetailVo();
        validQuery.setBatchId(batchId);
        validQuery.setStatus(1L);
        validQuery.setTenantId(tenantId);
        List<BatchLogDetailVo> validRecords = batchLogDetailMapper.selectBatchLogDetailList(validQuery);

        if (validRecords.isEmpty()) {
            return "没有数据可导入！";
        }

        // 检查学生是否已存在
        for (BatchLogDetailVo record : validRecords) {
            StudentInfoVo studentQuery = new StudentInfoVo();
            studentQuery.setIdNumber(record.getIdNumber());
            studentQuery.setName(record.getName());
            List<StudentInfoVo> existingStudents = studentInfoMapper.selectStudentInfotoList(studentQuery);

            if (!existingStudents.isEmpty()) {
                return "有学生信息已提前导入过，姓名：" + record.getName();
            }
        }

        // 批量处理学生信息导入
        for (BatchLogDetailVo record : validRecords) {
            try {
                processStudentRecord(record, tenantId, graduateStatus);
            } catch (Exception e) {
                log.info("处理学生信息失败，姓名：{}，身份证号：{}", record.getName(), record.getIdNumber(), e);
                throw new RuntimeException("导入学生信息失败：" + record.getName(), e);
            }
        }

        // 更新批次状态
        studentBatchLogMapper.updateByBatchId(batchId);
        return "导入成功！";
    }


    /**
     * 处理单条学生记录
     *
     * @param record 批次详情记录
     * @param tenantId 租户ID
     * @param graduateStatus 毕业状态
     */
    private void processStudentRecord(BatchLogDetailVo record, Integer tenantId, Long graduateStatus) {
        // 处理学院信息
        Long collegeId = null;
        Long campusId = null;
        R<List<SchoolCollegeVos>> collegeResult = null; // 初始化变量
        if (StringUtils.hasText(record.getCollegeName())) {
            SchoolCollegeVos collegeQuery = new SchoolCollegeVos();
            collegeQuery.setCollegeName(thoroughCleanString(record.getCollegeName().trim()));
            collegeQuery.setDeleteFlag("0");
            collegeResult = remoteEduService.checkCollege(collegeQuery);

            if (collegeResult != null && collegeResult.getData() != null && !collegeResult.getData().isEmpty()) {
                collegeId = collegeResult.getData().get(0).getId();
                campusId = collegeResult.getData().get(0).getCampusId();
                record.setCollegeId(collegeId);
            }
        }

        // 处理年级信息
        if (StringUtils.hasText(record.getGradeName())) {
            SchoolGradeVos gradeQuery = new SchoolGradeVos();
            gradeQuery.setGrade(thoroughCleanString(record.getGradeName().trim()));
            gradeQuery.setDeleteFlag("0");
            gradeQuery.setStatus("1");
            R<List<SchoolGradeVos>> gradeResult = remoteEduService.checkGrade(gradeQuery);

            if (gradeResult != null && gradeResult.getData() != null && !gradeResult.getData().isEmpty()) {
                record.setGradeId(gradeResult.getData().get(0).getId());
            }
        }

        // 处理学历信息
        R<List<CollegeModelVos>> educationResult = null; // 初始化变量
        if (collegeId != null && StringUtils.hasText(record.getEducation())) {
            CollegeModelVos educationQuery = new CollegeModelVos();
            educationQuery.setModelName(thoroughCleanString(record.getEducation().trim()));
            educationQuery.setCollegeName(thoroughCleanString(record.getCollegeName().trim()));
            educationQuery.setCampusId(campusId);
            educationQuery.setDeleteFlag("0");
            educationQuery.setStatus("1");
            educationResult = remoteEduService.checkEducation(educationQuery);

            if (educationResult != null && educationResult.getData() != null && !educationResult.getData().isEmpty()) {
                record.setEducationId(educationResult.getData().get(0).getId());
            }
        }

        // 处理专业信息
        if (collegeId != null && StringUtils.hasText(record.getMajorName())) {
            CollegeMajorVos majorQuery = new CollegeMajorVos();
            majorQuery.setCollegeIds(String.valueOf(collegeId));
            majorQuery.setMajorName(thoroughCleanString(record.getMajorName().trim()));
            // 修复变量引用错误，使用educationResult而不是未定义的modelResult
            if (educationResult != null && educationResult.getData() != null && !educationResult.getData().isEmpty()) {
                majorQuery.setModelId(educationResult.getData().get(0).getId());
            }
            majorQuery.setDeleteFlag("0");
            majorQuery.setStatus("1");
            R<List<CollegeMajorVos>> majorResult = remoteEduService.checkMajor(majorQuery);

            if (majorResult != null && majorResult.getData() != null && !majorResult.getData().isEmpty()) {
                record.setMajorId(majorResult.getData().get(0).getId());
            }
        }

        // 处理校区信息
        if (campusId != null) {
            SchoolCampusVos campusQuery = new SchoolCampusVos();
            campusQuery.setId(campusId);
            campusQuery.setDeleteFlag("0");
            campusQuery.setStatus("1");
            R<List<SchoolCampusVos>> campusResult = remoteEduService.checkCampus(campusQuery);
            if (campusResult != null && campusResult.getData() != null && !campusResult.getData().isEmpty()) {
                record.setCampusId(campusResult.getData().get(0).getId());
                record.setBranchName(campusResult.getData().get(0).getCampusName());
            }
        }

        // 构建学生信息对象
        StudentInfo studentInfo = buildStudentInfo(record, tenantId);
        // 设置毕业状态
        studentInfo.setGraduate(graduateStatus);
        // 插入学生信息
        studentInfoMapper.insertStudentInfo(studentInfo);
    }


    /**
     * 构建学生信息对象
     *
     * @param record 批次详情记录
     * @param tenantId 租户ID
     * @return 学生信息对象
     */
    private StudentInfo buildStudentInfo(BatchLogDetailVo record, Integer tenantId) {
        StudentInfo studentInfo = new StudentInfo();

        // 基本信息
        studentInfo.setName(record.getName());
        studentInfo.setIdNumber(record.getIdNumber());
        studentInfo.setPhone(record.getPhone());

        // 性别转换
        if (StringUtils.hasText(record.getSex())) {
            if ("男".equals(record.getSex())) {
                studentInfo.setSex(1L); // 男
            } else if ("女".equals(record.getSex())) {
                studentInfo.setSex(0L); // 女
            }
        }

        // 学院信息
        studentInfo.setCollegeId(record.getCollegeId());
        studentInfo.setCollegeName(record.getCollegeName());

        // 学历信息
        studentInfo.setEducationId(record.getEducationId());
        studentInfo.setEducation(record.getEducation());

        // 专业信息
        studentInfo.setMajorId(record.getMajorId());
        studentInfo.setMajorName(record.getMajorName());

        // 年级信息
        studentInfo.setGradeId(record.getGradeId());
        studentInfo.setGradeName(record.getGradeName());

        // 班级信息
        studentInfo.setClassName(record.getClassName());

        // 学制信息
        studentInfo.setSchoolSystem(record.getSchoolSystem());

        // 时间信息
        studentInfo.setSignTime(new Date());
        studentInfo.setCreateTime(new Date());
        studentInfo.setUpdateTime(new Date());

        // 状态信息
        studentInfo.setSignStatus(1L);   // 1预报名成功

        studentInfo.setSealStatus(0L);   // 0未封存
        studentInfo.setIsDel(0);         // 未删除

        // 租户信息
        studentInfo.setTenantId(tenantId);
        if (record.getCampusId() != null) {
            studentInfo.setCompusId(Math.toIntExact(record.getCampusId()));
        }
        studentInfo.setBranchName(record.getBranchName());

        return studentInfo;
    }

    /**
     * 更彻底地清理字符串
     * @param str 原始字符串
     * @return 清理后的字符串
     */
    private String thoroughCleanString(String str) {
        if (str == null) return null;
        // 去除首尾空格，然后去除所有特殊字符，只保留字母、数字、中文字符、空格和常见符号
        if (str == null) return null;
        // 去除首尾空白字符，将中间的换行符、制表符等替换为空格，然后将多个空格合并为单个空格
        return str.trim()
                .replaceAll("[\\r\\n\\t]", " ")
                .replaceAll("\\s+", " ");
    }

}
